import ajaxAsync from 'vue-xiaobu-utils'
import BusInfoModel from '../models/BusInfoModel'
import RouterModel from '../models/RouterModel'
import StationModel from '../models/StationModel'
import { getAssociateListByAmap } from './amapapi.js'
/**
 * 查询公交路线、车站
 * @param {Number}  pageNo 页码
 * @param {Number} pageSize 每页条数
 * @param {String} searchText 输入查询文本
 */
function getBusRouterStationInfo(pageNo, pageSize, searchText) {
  let sendObj = {
    IMPORT: searchText,
    PAGE_CAPACITY: pageSize,
    PAGE_INDEX: pageNo
  }
  let busInfoModel = {}
  return new Promise((resolve, reject) => {
    ajaxAsync('/bus/import', sendObj).then(res => {
      // 线路
      let busList = []
      if (res.BUS_LIST && res.BUS_COUNT > 0) {
        res.BUS_LIST.map((item, index) => {
          // 处理不包含中文
          var reg = /[\u4e00-\u9fa5]+/
          item.NAME = !reg.test(item.NAME) ? item.NAME + '路' : item.NAME
          let routerModel = new RouterModel(item.ID, item.NAME, item.TYPE)
          busList.push(routerModel)
        })
      }
      // 站点下线路
      let stationList = []
      if (res.STATION_LIST && res.STATION_COUNT > 0) {
        res.STATION_LIST.map((item, index) => {
          let stationModel = new StationModel(
            item.ID,
            item.NAME,
            item.TYPE,
            item.LATITUDE,
            item.LONGITUDE
          )
          stationList.push(stationModel)
        })
      }
      busInfoModel = new BusInfoModel(
        res.BUS_COUNT,
        res.STATION_COUNT,
        busList,
        stationList
      )
      resolveBody(busInfoModel, resolve)
    })
    // TODO:根据高德api获取位置列表
    getAssociateListByAmap(
      sendObj.IMPORT,
      sendObj.PAGE_INDEX,
      sendObj.PAGE_CAPACITY
    )
      .then(res => {
        let amapList = []
        let amapCount = 0
        amapList = res.poiList.pois
        amapCount = res.poiList.count
        if (amapList.length > 0) {
          amapList.map((item, index) => {
            item.longitude = item.location.lng
            item.latitude = item.location.lat
          })
        }
        busInfoModel.amapList = amapList
        busInfoModel.amapCount = amapCount
        resolveBody(busInfoModel, resolve)
      })
      .catch(error => {
        console.log(error)
      })
  })
}

// 判断2个协议是否都完成
function resolveBody(body, resolve) {
  // console.log(Object.keys(body).length)
  if (Object.keys(body).length === 6) {
    resolve(body)
  }
  // if (body.amapList && body.busList && body.stationList) {
  //   resolve(body)
  // }
}

export { getBusRouterStationInfo }
